# -*- coding: utf-8 -*-
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse
from django.conf import settings
import re


class Rbac(MiddlewareMixin):
	'''基于角色的访问控制'''
	def process_request(self, request):
		# 获取url
		url = request.path_info
		# 在白名单中返回
		for white_url in settings.WHITE_LIST:
			if re.match(white_url, url):
				return

		# 检查用户是否登录，在免登陆中返回
		is_login = request.session.get('is_login')
		if is_login == '1':
			for no_permission_url in settings.NO_PERMISSION_LIST:
				if re.match(no_permission_url, url):
					return

		# 获取用户的权限列表，匹配成功返回，否则返回没有权限
		permissions = request.session.get('permissions')
		for permission in permissions:
			if re.match(r'^{}$'.format(permission['permissions__url']), url):
				return

		return HttpResponse('没有权限访问，请联系管理员！')